package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.aop.annotation.LogAnnotation;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.*;
import com.company.project.service.FileHandleService;
import com.company.project.service.ResumeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import oracle.jdbc.proxy.annotation.Post;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@RequestMapping("/resume")
@RestController
@Api(tags = "下载文件-下载文件管理")
public class ResumeController {
    @Value("${files.uploadDir}")
    String uploadDir;//文件存储根路径
    @Resource
    private ResumeService resumeService;

    @Autowired
    private DocumentConverter converter;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private FileHandleService fileHandleService;

    @ApiOperation(value = "查询数据")
    @PostMapping("/list")
    @RequiresPermissions("resume:list")
    public DataResult findListByPage(@RequestBody SysResume vo) {
        Page page = new Page(vo.getPage(), vo.getLimit());
        LambdaQueryWrapper<SysResume> queryWrapper = Wrappers.lambdaQuery();
        if (!StringUtils.isEmpty(vo.getId())) {
            queryWrapper.like(SysResume::getId, vo.getId());
        }
        if (!StringUtils.isEmpty(vo.getName())) {
            queryWrapper.like(SysResume::getName, vo.getName());
        }
        if (!StringUtils.isEmpty(vo.getEmail())) {
            queryWrapper.like(SysResume::getEmail, vo.getEmail());
        }
        if (!StringUtils.isEmpty(vo.getPhone())) {
            queryWrapper.like(SysResume::getPhone, vo.getPhone());
        }
        if (!StringUtils.isEmpty(vo.getCreateTime())) {
            queryWrapper.like(SysResume::getCreateTime, vo.getCreateTime());
        }
        queryWrapper.orderByAsc(SysResume::getId);
        return DataResult.success(resumeService.page(page, queryWrapper));
    }

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    @ResponseBody
    public DataResult uploadFile(MultipartFile file, HttpServletRequest request) {
        if (file != null) {
            FileMsg fileMsg = fileHandleService.fileuploadhandle(file, request);
            return DataResult.success(fileMsg);
        }
        return null;
    }

    @ApiOperation(value = "文件扫描上传")
    @PostMapping(value = "/scan", headers = "content-type=multipart/form-data")
    public DataResult scan(MultipartFile file, HttpServletRequest request) {
        if (file != null) {
            FileMsg fileMsg = fileHandleService.scan(file, request);
            return DataResult.success(fileMsg);
        }
        return null;
    }


    @ApiOperation(value = "文件预览")
    @GetMapping("/preview")
    public DataResult preview(Integer id) {
        System.out.println(id);
        String pdfUrl = resumeService.findUrl(id);
        File file = new File(uploadDir + File.separator + "2pdf" + File.separator  + pdfUrl);//需要转换的文件
        try {
            //使用response,将pdf文件以流的方式发送的前段
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(file);// 读取文件
            // copy文件
            int i = IOUtils.copy(in, outputStream);
            System.out.println(i);
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DataResult.success();
    }

    /**
     * 新增
     */
    @ApiOperation(value = "新增数据")
    @PostMapping("/add")
    @RequiresPermissions("resume:add")
    public DataResult save(@RequestBody SysResume sysResume) {

        String checkSysResume = checkSysResume(sysResume);
        if (!"success".equals(checkSysResume))
            return DataResult.fail(checkSysResume);
        Integer result = resumeService.saves(sysResume);
        if (result < 0)
            return DataResult.fail("新增失败");
        return DataResult.success(result);
    }

    /**
     * 修改
     */
    @ApiOperation(value = "修改数据")
    @PostMapping("/update")
    @RequiresPermissions("resume:update")
    public DataResult update(@RequestBody SysResume sysResume) {

        String checkSysResume = checkSysResume(sysResume);
        if (!"success".equals(checkSysResume))
            return DataResult.fail(checkSysResume);
        Integer result = resumeService.updateByIds(sysResume);
        if (result < 0)
            return DataResult.fail("修改失败");
        return DataResult.success(result);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    @RequiresPermissions("resume:delete")
    @LogAnnotation(title = "删除")
    public DataResult deleted(@RequestBody List<Long> ids) {
        resumeService.removeByIds(ids);
        return DataResult.success();
    }

    /**
     * 模糊查询
     */
    @PostMapping("/findBySome")
    public DataResult some(@RequestParam String name, String phone, String email) {

        return DataResult.success(resumeService.findBySome(name, phone, email));
    }

    private String checkSysResume(SysResume sysResume) {
        if (sysResume == null)
            return "请按要求填写信息";
        if (StringUtils.isEmpty(sysResume.getName()))
            return "姓名不能为空";
        if (StringUtils.isEmpty(sysResume.getEmail()))
            return "邮件不能为空";
        if (StringUtils.isEmpty(sysResume.getPhone()))
            return "电话不能为空";
        return "success";
    }
}

